# -*-coding:utf-8-*-
from __future__ import unicode_literals

import copy
import datetime
import re
import sys
import time

from .logic_adapter import LogicAdapter
from ..zyrobot.mysqlconn import conn
from logging import getLogger

web_logger = getLogger('web_logger')


class newStatementclass(object):

    def __init__(self, text, **kwargs):

        try:
            text = str(text)
        except UnicodeEncodeError:
            pass

        self.text = text
        self.confidence = 0


class BestMatchquestion(LogicAdapter):
    """
    A logic adater that returns a response based on known responses to
    the closest matches to the input statement.

    """

    def get(self, input_statement):
        """
        Takes a statement string and a list of statement strings.
        Returns the closest matching statement from the list.


        """
        web_logger.debug('serviceid:%s input_statement:%s', self.serviceid, input_statement)
        statement_list = self.chatbot.storage.get_response_statements()

        closest_match = input_statement

        closest_match.confidence = self.confidence_threshold

        for statement in statement_list:
            confidence = self.compare_statements(statement, input_statement)
            web_logger.debug('serviceid:%s input_statement:%s statement:%s confidence:%s', self.serviceid,
                             input_statement, statement, confidence)
            if confidence > closest_match.confidence:
                statement.confidence = confidence
                closest_match = statement
        web_logger.debug('closest_match:%s', closest_match)
        return closest_match

    def selhavebackanswerid(self, cid, serviceid):
        sql = "select r.answerid from zy_rcustomerquestion q,zy_robotanswer r  \
        where q.cid='" + str(cid) + "' and q.serviceid=" + str(
            serviceid) + " and q.sessionid=r.sessionid and r.answerid is not NULL GROUP BY  answerid"
        answeridgroup = conn.mysql_sel(sql, self.dbname, self.cid)
        # print('sql',sql)
        return answeridgroup

    def can_process(self, statement):
        """
        Check that the chatbot's storage adapter is available to the logic
        adapter and there is at least one statement in the database.

        """
        # return self.chatbot.storage.count()
        return True

    def fuzzyquery(self, cmpid, serviceid, text, industryid):
        sql = "select  q.quesid,q.keywords from zt_know_question q where q.cmpid=" + str(
            cmpid) + " and q.serviceid=" + str(serviceid) + " and q.keywords!='' and q.state=1 "

        keywords = conn.mysql_sel(sql, self.dbname, self.cid)

        return keywords

    def selanswerid(self, quesid):
        sql = "select a.answerid from zt_know_answer a where a.quesid=" + str(quesid) + " ORDER BY a.sort  LIMIT 0,1"

        answerid = conn.mysql_selrowid(sql, self.dbname, self.cid)
        return answerid

    def tracommfuzzyquery(self, cmpid, serviceid, text, industryid):
        sql = "select  q.quesid,q.keywords from zt_know_question q where  q.keywords!='' and q.state=1 "

        if industryid != None and industryid != "":
            sql = sql + " and industryid= '" + str(industryid) + "'"
        keywords = conn.mysql_sel(sql, self.dbname, self.cid)

        return keywords

    def selfuzzyqueryanswer(self, keywork, cmpid, serviceid):
        sql = "select q.answerid from zt_know_question q where q.cmpid=" + str(cmpid) + " and" \
                                                                                        " q.serviceid=" + str(
            serviceid) + " and  FIND_IN_SET( '" + str(keywork) + "',q.keywords) ORDER BY q.createtime DESC LIMIT 0,1"
        keywords = conn.mysql_selrowid(sql, self.dbname, self.cid)

        return keywords

    def fromquestion(self, answerid):
        sql = "select a.quesid from zt_know_answer a where a.answerid=" + str(answerid) + " "
        print(" def fromquestion中的sql", sql)
        questionid = conn.mysql_selrowid(sql, self.dbname, self.cid)
        print(" def fromquestion中的questionid", questionid)
        return questionid

    def insertquestion(self, answerid, cid, cmpid):
        sql = "select a.quesid from zt_know_answer a where a.answerid=" + str(answerid) + " "
        questionid = conn.mysql_selrowid(sql, self.dbname, cid)
        if questionid == None or questionid == '':
            sql = "select q.quesid from zt_know_question q where q.answerid=" + str(answerid) + ""
            questionid = conn.mysql_selrowid(sql, self.dbname, cid)

        insertcount = str(0)

        if questionid != conn.err:
            sqlinsert = "INSERT into zt_cmp_robot_respond(cmpid,cid,questionid,session_data,session_sort) VALUES ('" + str(
                cmpid) + "','" + str(cid) + "','" + str(
                questionid) + "','" + self.session_data + "','" + self.session_sort + "')"

            insertcount = conn.mysql_insert(sqlinsert, self.dbname, cid)

        return str(insertcount)

    def ifhoodlemobole(self, askid):
        sql = "select a.attitude from zt_know_hoodlemobile_answer a where a.HoodleMobileid='" + str(
            askid) + "' ORDER BY a.attitude "
        attitudelist = conn.mysql_sel(sql, self.dbname, self.cid)

        attitudelist = attitudelist + ((6,), (7,), (11,))
        return attitudelist

    # 查询技能
    def selskill(self, serviceid):
        sql = "SELECT s.skillid,s.keywords from zt_skill s  where s.state=1 and keywords!='' and keywords is not null and s.serviceid='" + str(
            serviceid) + "'"
        keywords = conn.mysql_sel(sql, self.dbname, self.cid)

        return keywords

    def backanswer(self, statement_list, closest_match, input_statement):
        if statement_list != None and len(statement_list) != 0:
            closest_match.confidence = 0.85

            maxsocre = 0
            maxtext = ''
            for statement in statement_list:
                print(statement)
                socre = 1
                if statement.text.count('$') >= 1:
                    socre = statement.text.split('$')[-1]
                    newstatement = statement.text[:statement.text.rfind('$')]

                    # print('33',newstatement,socre)
                    if newstatement.strip() != "" and newstatement.strip() in str(input_statement):
                        if float(socre) == float(maxsocre):
                            if len(statement.text) > len(maxtext):
                                maxtext = statement.text
                                maxsocre = socre
                                web_logger.debug('socre=maxsocre  serviceid:%s maxtext:%s maxsocre:%s', self.serviceid,
                                                 maxtext, maxsocre)
                        elif float(socre) > float(maxsocre):
                            maxtext = statement.text
                            maxsocre = socre
                            web_logger.debug('socre>maxsocre  serviceid:%s maxtext:%s maxsocre:%s', self.serviceid,
                                             maxtext, maxsocre)

                ottherstatement = copy.deepcopy(statement)

                if statement.text.count('$') >= 1:
                    ottherstatement.text = str(statement.text).split('$')[0]
                if ottherstatement != "":
                    confidence = self.compare_statements(ottherstatement, input_statement)
                    print('2', confidence, 'confidence', statement, ottherstatement)
                else:
                    confidence = 0
                if confidence > closest_match.confidence:
                    web_logger.debug('confidence >closest_match.confidence  '
                                     'serviceid:%s confidence:%s statement:%s input_statement:%s',
                                     self.serviceid, confidence, statement, input_statement)
                    statement.confidence = confidence
                    closest_match = statement

            if maxsocre != 0 and closest_match.confidence != 1:
                # closest_match.confidence = maxsocre
                # closest_match.text = maxtext

                response_list = self.chatbot.storage.filter(
                    in_response_to__contains=maxtext
                )
                if len(response_list) != 0:
                    response = self.select_response(input_statement, response_list)
                    response.confidence = maxsocre

                    if response.text != self.default_response:
                        response.text = 'attitude' + response.text

                    return response

            response_list = self.chatbot.storage.filter(
                in_response_to__contains=closest_match.text
            )
            if len(response_list) != 0:
                response = self.select_response(input_statement, response_list)
                response.confidence = closest_match.confidence

                if response.text != self.default_response:
                    response.text = 'attitude' + response.text

                return response

    def selmongodbdata(self, data, tablename):
        statement_data = self.chatbot.storage.get_response_statements_database(data, tablename)
        if len(statement_data) != 0:
            statement_list = statement_data
            return statement_list

    # 查询公共行业问题
    def selindustrycomm(self, industryid, closest_match, input_statement):
        ifhavetable = self.chatbot.storage.seltable('industry' + str(industryid), '')
        print('def selindustrycomm中的 ifhavatable', ifhavetable)
        if str(ifhavetable) != '0':
            statement_data = self.selmongodbdata('industry' + str(industryid), '')
            web_logger.debug('serviceid:%s industry:%s', self.serviceid, industryid)
            backanswerdata = self.backanswer(statement_data, closest_match, input_statement)
            if backanswerdata != None:
                alltext = backanswerdata.text[8:]
                allconfidence = backanswerdata.confidence
                return (allconfidence, alltext)

    def attitudejudge(self, closest_match, input_statement):

        alltext = ''
        allconfidence = 0
        updatelist = 0
        attitudelist = self.ifhoodlemobole(self.askid)
        if attitudelist == ((5,), (6,), (7,), (11,)):
            updatelist = 1
            attitudelist += ((1,), (2,), (3,))

        ifhavetable = self.chatbot.storage.seltable('database' + str(self.cmpid) + '-HoodleMobile' + str(self.askid),
                                                    str(self.dbname) + 'database' + str(self.cmpid))

        if str(len(attitudelist)) != '0':
            if str(ifhavetable) != '0':
                statement_data = self.selmongodbdata('database' + str(self.cmpid) + '-HoodleMobile' + str(self.askid),
                                                     str(self.dbname) + 'database' + str(self.cmpid))
                # print(statement_data)

                backanswerdata = self.backanswer(statement_data, closest_match, input_statement)

                if backanswerdata != None:
                    alltext = backanswerdata.text
                    allconfidence = backanswerdata.confidence
            if allconfidence != 1:
                print('attitudelist', attitudelist)
                for attitude in attitudelist:

                    statement_data = self.selmongodbdata('answertype' + str(attitude[0]), '')
                    web_logger.debug('serviceid:%s attitude:%s answertype:%s statement_data:%s',
                                     self.serviceid, attitude, attitude[0], statement_data)
                    backanswerdata = self.backanswer(statement_data, closest_match, input_statement)
                    print(backanswerdata)
                    if backanswerdata != None:
                        if backanswerdata.confidence != 1:
                            web_logger.debug('serviceid:%s attitude:%s answertype:%s confidence allconfidence',
                                            self.serviceid, attitude, attitude[0], backanswerdata.confidence,
                                            allconfidence)
                            if float(backanswerdata.confidence) == float(allconfidence):
                                if len(backanswerdata.text) > len(alltext):
                                    allconfidence = backanswerdata.confidence
                                    alltext = backanswerdata.text
                            elif float(backanswerdata.confidence) > float(allconfidence):
                                allconfidence = backanswerdata.confidence
                                alltext = backanswerdata.text
                        else:
                            # print('ff','answertype'+str(attitude[0]))
                            allconfidence = backanswerdata.confidence
                            alltext = backanswerdata.text

        if updatelist == 1:
            if alltext[:-1] == 'attitude' or alltext[:-2] == 'attitude':
                if str(alltext[8:]) == '1' or str(alltext[8:]) == '2' or str(alltext[8:]) == '3':
                    alltext = 'attitude5'

        return (allconfidence, alltext)

    def groo_keywork(self, input_statement, response):
        keywords = self.fuzzyquery(self.cmpid, self.serviceid, input_statement, '')
        if len(keywords) != 0:
            quesid = ''
            maxkeywordtext = ''
            for i in keywords:
                worklist = []
                try:
                    newzheng = i[1].replace(",", "|")
                    pipe_word = re.compile(newzheng)
                    worklist = re.findall(pipe_word, input_statement.text)
                except:
                    web_logger.debug('serviceid:%s keyword:%s', self.serviceid, i)
                if len(worklist) != 0:
                    worklen = 0
                    workend = ''
                    for work in worklist:
                        if len(work) > worklen:
                            worklen = len(work)
                            workend = work

                    if maxkeywordtext != "":

                        if worklen > len(maxkeywordtext):
                            quesid = i[0]
                            maxkeywordtext = workend
                    else:
                        quesid = i[0]
                        maxkeywordtext = workend

            if maxkeywordtext != "":
                web_logger.debug('serviceid:%s quesid:%s maxkeywordtext:%s', self.serviceid, quesid, maxkeywordtext)
                response.text = 'A' + str(quesid)
                response.confidence = 1
                return response

    # 态度正则查询
    def sel_reg_data(self):
        sql = "SELECT a.regwords,a.attitude from zt_know_hoodlemobile_answer a where a.HoodleMobileid='" + str(
            self.askid) + "' and a.regwords!='' and a.regwords is not NULL"
        regword = conn.mysql_sel(sql, self.dbname, self.cid)
        return regword

    def pipe_reg_attitue(self, input_statement, response):
        regwordslist = self.sel_reg_data()
        # #(regwordslist)
        attitudedata = ''
        if len(regwordslist) != 0:
            maxkeywordtext = ""
            for regwords in regwordslist:
                worklist = []
                try:
                    # print(0,regwords)
                    regdata = regwords[0].replace(",", "|")
                    # print(regdata)
                    pipe_word = re.compile(regdata)
                    # print(2,pipe_word)
                    worklist = re.findall(pipe_word, input_statement.text)
                except:
                    web_logger.debug('serviceid:%s regwords:%s', self.serviceid, regwords)

                if len(worklist) != 0:
                    worklen = 0
                    workend = ''
                    for work in worklist:
                        if len(work) > worklen:
                            worklen = len(work)
                            workend = work

                    if maxkeywordtext != "":

                        if worklen > len(maxkeywordtext):
                            attitudedata = regwords[1]
                            maxkeywordtext = workend
                    else:
                        attitudedata = regwords[1]
                        maxkeywordtext = workend

            if maxkeywordtext != "":
                web_logger.debug('serviceid:%s attitude:%s maxkeywordtext:%s', self.serviceid, attitudedata,
                                maxkeywordtext)
                response.text = 'attitude' + str(attitudedata)
                response.confidence = 1
                return response

    def process(self, input_statement):

        closest_match = self.get(input_statement)

        self.logger.info('Using "{}" as a close match to "{}"'.format(
            input_statement.text, closest_match.text
        ))

        # Get all statements that are in response to the closest match
        response_list = self.chatbot.storage.filter(
            in_response_to__contains=closest_match.text
        )

        if response_list:
            self.logger.info(
                'Selecting response from {} optimal responses.'.format(
                    len(response_list)
                )
            )

            response = self.select_response(input_statement, response_list)
            # print('response',response,response.text,response.text[1:])
            response.confidence = closest_match.confidence
            response.text = 'A' + str(self.fromquestion(response.text[1:]))
            self.logger.info('Response selected. Using "{}"'.format(response.text))

            if self.cmpid != '-1' and self.serviceid != '-1' and self.cid != '-1' and self.askid != '-1' and response.confidence != 1:
                # attitudelist = self.ifhoodlemobole(self.askid)
                data = self.groo_keywork(input_statement, response)
                # print(data)
                if data != None:
                    return data
            response.confidence = 1
            web_logger.debug('cid:%s serviceid:%s ', self.cid, self.serviceid)
        else:
            # response = self.chatbot.storage.get_random()
            response = closest_match
            if self.cmpid != '-1' and self.serviceid != '-1' and self.cid != '-1' and self.askid != '-1':

                data = self.groo_keywork(input_statement, response)
                if data != None:
                    return data

                # response = closest_match
                # response.confidence = 1
                # response.text = 'notnext'
                # return response
            else:

                response.confidence = 0
                response.text = self.default_response

            self.logger.info(
                'No response to "{}" found. Selecting a random response.'.format(
                    closest_match.text
                )
            )
        # print('responsessssss',response)
        return response
